import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_chat_global_model.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:yqmssa_app/config/app_config.dart';
import 'package:yqmssa_app/utils/shared_utils.dart';
import 'package:yqmssa_app/utils/tencent_im_utils.dart';
import 'package:yqmssa_app/utils/wx_utils.dart';
import 'package:yqmssa_app/views/index/request/message_request.dart';

import 'human_customer_manager.dart';

class HumanCustomerView extends StatelessWidget {
  const HumanCustomerView({super.key});

  @override
  Widget build(BuildContext context) {
    final manager = Get.put(HumanCustomerManager());
    return GestureDetector(
      onTap: FocusScope.of(context).unfocus,
      child: Scaffold(
        body: Obx(() {
          return GestureDetector(
            onTap: FocusScope.of(context).unfocus,
            child: TIMUIKitChat(
              conversationID: manager.data.value.serviceTencentId,
              conversationType: ConvType.c2c,
              controller: manager.controller,
              conversationShowName: '',
              textFieldHintText: "描述您的问题",
              config: const TIMUIKitChatConfig(isAllowEmojiPanel: false, isAllowShowMorePanel: false, isAllowSoundMessage: false, isShowReadingStatus: false),
              userAvatarBuilder: (context, user) {
                if (!user.nickName!.isPhoneNumber) {
                  return Image.asset(AppConfig.imagePath("customer_avatar.png"), width: 46);
                } else {
                  return Image.asset(AppConfig.imagePath("self_avatar.png"), width: 46);
                }
              },
              messageItemBuilder: MessageItemBuilder(customMessageItemBuilder: (v2Message, val, obj) {
                if ((v2Message.customElem?.data ?? "").isNotEmpty) {
                  final data = jsonDecode(v2Message.customElem?.data ?? "");
                  return GestureDetector(
                    onTap: () async {
                      if (AppConfig.appInitData.jumpXcx == 1) {
                        AppConfig.launchLink(sharedUtils.service?.customerAcquisition ?? "");
                        MessageRequest.updateIsDistinguish();
                      } else {
                        WechatUtils.pushWxXcx(sharedUtils.service?.id ?? 0);
                      }
                    },
                    child: Container(
                      width: 240,
                      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(4)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Image.network(
                                data["avatars"] ?? "",
                                width: 56,
                                errorBuilder: (context, obj, st) {
                                  return Image.asset(
                                    AppConfig.imagePath("wei2.png"),
                                    width: 56,
                                  );
                                },
                              ),
                              const SizedBox(width: 8),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    data["title"] ?? "点击此处",
                                    style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                                  ),
                                  Text(
                                    data["desc"] ?? "立刻添加法务微信",
                                    style: const TextStyle(
                                      fontSize: 12,
                                    ),
                                  ),
                                ],
                              )
                            ],
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 4),
                            child: Divider(color: Colors.grey.shade300, height: 1, thickness: 0.5),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 8),
                            child: Text(
                              "企业微信名片",
                              style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                } else {
                  return null;
                }
              }),
              inputTopBuilder: Container(
                color: const Color(0XFFF3F3F3),
                width: double.maxFinite,
                margin: const EdgeInsets.only(bottom: 12),
                child: Wrap(
                  spacing: 12,
                  children: [
                    const SizedBox(width: 4),
                    if (AppConfig.appInitData.haveCall == 1)
                      GestureDetector(
                          onTap: () async {
                            tencentImUtils.tellPhone();
                          },
                          child: Container(
                            height: 40,
                            width: 108,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(22),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset(AppConfig.imagePath("phone.png"), width: 16),
                                const SizedBox(width: 4),
                                const Text(
                                  "拨打电话",
                                  style: TextStyle(color: Color(0XFF444444), fontWeight: FontWeight.w500),
                                ),
                              ],
                            ),
                          )),
                    if (AppConfig.appInitData.addWxButton?.addWxView == 1)
                      GestureDetector(
                        onTap: () async {
                          tencentImUtils.addWeChat();
                        },
                        child: Container(
                          height: 40,
                          width: 108,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(22),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset(AppConfig.imagePath("wei.png"), width: 16),
                              const SizedBox(width: 4),
                              Text(
                                (AppConfig.appInitData.addWxButton?.chatWeText ?? "").isNotEmpty
                                    ? (AppConfig.appInitData.addWxButton?.chatWeText ?? "")
                                    : "添加微信",
                                style: const TextStyle(color: Color(0XFF444444), fontWeight: FontWeight.w500),
                              ),
                            ],
                          ),
                        ),
                      ),
                  ],
                ),
              ),
              textFieldBuilder: (context) {
                return Container(
                  color: Colors.white,
                  padding: const EdgeInsets.only(bottom: 12),
                  child: Padding(
                    padding: const EdgeInsets.all(12),
                    child: Row(
                      children: [
                        Expanded(
                          child: TextField(
                            controller: manager.controller.textFieldController?.textEditingController,
                            decoration: InputDecoration(
                              hintText: "点击发送消息",
                              hintStyle: const TextStyle(fontSize: 16, color: Colors.black38),
                              fillColor: const Color(0XFFF3F3F3),
                              filled: true,
                              contentPadding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(24),
                                borderSide: const BorderSide(width: 1, color: Color(0XFFDCDCDC)),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(24),
                                borderSide: const BorderSide(width: 1, color: Color(0XFFDCDCDC)),
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 12),
                        InkWell(
                          onTap: manager.sendText,
                          child: Container(
                            height: 40,
                            width: 64,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(colors: [Color(0XFFF4DDC2), Color(0XFFE4B591)]),
                              borderRadius: BorderRadius.circular(99),
                            ),
                            child: const Text("发送", style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
                return TIMUIKitInputTextField(
                  conversationID: manager.data.value.serviceTencentId,
                  conversationType: ConvType.c2c,
                  model: manager.controller.model!,
                  hintText: "描述您的问题",
                  isUseDefaultEmoji: false,
                  showMorePanel: false,
                  showSendAudio: false,
                  showSendEmoji: false,
                  morePanelConfig: MorePanelConfig(showFilePickAction: false),
                  currentConversation: V2TimConversation(
                    conversationID: manager.data.value.serviceTencentId,
                    type: 1,
                    userID: manager.data.value.serviceTencentId,
                  ),
                );
              },
              appBarConfig: AppBar(
                backgroundColor: Colors.white,
                foregroundColor: Colors.white,
                surfaceTintColor: Colors.white,
                leading: IconButton(
                  onPressed: () {
                    Get.back();
                  },
                  icon: const Icon(
                    Icons.arrow_back_ios_new_rounded,
                    color: Colors.black,
                  ),
                ),
                flexibleSpace: Container(
                  decoration: const BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        Colors.white,
                        Colors.white,
                      ],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ),
                  ),
                ),
                centerTitle: true,
                title: const Text("逾期小助手"),
                titleTextStyle: const TextStyle(color: Color(0XFF333333), fontSize: 18, fontWeight: FontWeight.w500),
                elevation: 0,
              ),
              conversation: V2TimConversation(conversationID: manager.data.value.serviceTencentId, type: 1, userID: manager.data.value.serviceTencentId),
            ),
          );
        }),
      ),
    );
  }
}

Widget myStickerPanel({
  required void Function() sendTextMessage,
  required void Function(int index, String data) sendFaceMessage,
  required void Function() deleteText,
  required void Function(int unicode) addText,
  required void Function(String singleEmojiName) addCustomEmojiText,
  required List<CustomEmojiFaceData> defaultCustomEmojiStickerList,
  double? width,
  double? height,
}) {
  // 这里可以自定义你的表情面板 UI
  return Container(
    width: width,
    height: height,
    child: Column(
      children: [
        // 你的表情、按钮等
        ElevatedButton(
          onPressed: sendTextMessage,
          child: const Text('发送文本'),
        ),
        // 其它功能...
      ],
    ),
  );
}
